﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using MC.RideEvent.Mvc.Models.Entity;
using MC.RideEvent.Mvc.Models.ViewModel;
using AutoMapper;

namespace MC.RideEvent.Mvc.Models.Repository
{
    public class PreferenceRepository : IPreferenceRepository
    {
        private RideEventDBEntities _context;

        public PreferenceRepository()
        {
            _context = new RideEventDBEntities();
        }

        /// <summary>
        /// This method return the preference of vehicule
        /// whose vehiculeId parameter is matched.
        /// </summary>
        /// <param name="vehiculeId"></param>
        /// <returns></returns>
        public PreferenceModel GetPreferenceByMemberId(int memberId)
        {
            var preference = (from p in _context.Preferences
                              where p.MemberId == memberId
                              select p).FirstOrDefault();

            var data = Mapper.Map<Preference, PreferenceModel>(preference);

            return data;
        }

        public bool SavePreference(PreferenceModel preference, int memberId, bool isUpdate)
        {
            Preference p = null;

            if(isUpdate)
            {
                p = UpdatePreference(preference);
                _context.Entry(p);
                _context.Entry(p).State = EntityState.Modified;
            }
            else
            {
                p = CreatePreference(preference, memberId);
                _context.Preferences.Add(p);
            }

            var result = Convert.ToBoolean(_context.SaveChanges());

            return result;
        }

        private Preference CreatePreference(PreferenceModel preference, int memberId)
        {
            var dateNow = DateTime.Now;

            var pref = new Preference();
            pref.Age = preference.Age;
            pref.Smoker = preference.Smoker;
            pref.Music = preference.Music;
            pref.MemberId = memberId;
            pref.DriverStyleId = preference.DriverStyleId;
            pref.DateCreation = dateNow;
            pref.DateUpdate = dateNow;

            return pref;
        }

        private Preference GetPreferenceById(int preferenceId)
        {
            var p = (from pr in _context.Preferences
                     where pr.Id == preferenceId
                     select pr).FirstOrDefault();

            return p;
        }

        private Preference UpdatePreference(PreferenceModel preference)
        {
            var p = GetPreferenceById(preference.Id);

            if(p != null)
            {
                p.Age = preference.Age;
                p.Smoker = preference.Smoker;
                p.Music = preference.Music;
                p.DriverStyleId = preference.DriverStyleId;
                p.DateUpdate = DateTime.Now;
            }

            return p;
        }
    }
}
